window.onload = function(){



  var startButton = document.getElementById('start_button');
  var startPage = document.getElementById('start_page');
  var game_page = document.getElementById('game_page');
  var plane_container = document.getElementById('plane_container');
  var bulletSpeed = 10;
  var BULLETS = [];
  var ENEMIES = [];
  var ISGAMING = 0;
  var hero = null;
  var SCORE = 0;
  var bomb = document.getElementById('bomb');
  var score_panel = document.getElementById('score-panel');
  // var hero = document.getElementById('hero');


  /*  点击开始游戏 */
  startButton.onclick = function(){
    startGame();
  }


  function startGame(){
    startPage.style.display = 'none';
    ISGAMING = 1;
    /*  创建 hero 飞机*/
    if(ISGAMING === 1){
      hero = new Plane('img/hero.png',100,80,300,400);
      plane_container.appendChild(hero.imgNode)
    }
  }






  /*  创建 bullet*/
  var fireTimer = setInterval(function(){
      if(ISGAMING === 1){
        var bullet = new Bullet('img/bullet1.png',12,30,hero.x + 44,hero.y-10);
        plane_container.appendChild(bullet.imgNode)
        BULLETS.push(bullet);
      }
  },200)

  var fireEnemy = setInterval(function(){

      if(ISGAMING === 1){
        var x = Math.random()*412;
        var enemy = new Enemy('img/enemy1.png',100,100,x,0)
        ENEMIES.push(enemy);
        plane_container.appendChild(enemy.imgNode)
      }
  },1000)


  //刷新函数

  var update = function(){
    if(ISGAMING === 1){
      for(var i = 0;i < BULLETS.length;i++){
        var b = BULLETS[i];
          b.move(bulletSpeed);

          if(b.y < 0){

            BULLETS.splice(i,1)
            plane_container.removeChild(b.imgNode)
          }

          for (var j = 0; j < ENEMIES.length; j++) {
            var e = ENEMIES[j];
            var r = utils.collision(b,e);
            if(r){

              if(e && b){

                e.die()
                ENEMIES.splice(j,1)
                b.die()
                BULLETS.splice(i,1)

              }
              palyEffect()
              SCORE++;
              score_panel.innerHTML = SCORE;
            }
          }
      }

      for (var i = 0; i < ENEMIES.length; i++) {
        var e = ENEMIES[i];
        e.move(5);
        if(e.y > 768){
          ENEMIES.splice(i,1);
          plane_container.removeChild(e.imgNode)
        }

      }
    }

  }


  var updateTimer = setInterval(update,40)


 /*  件监听鼠标滑动事件，使hero跟随鼠标移动*/
  window.addEventListener('mousemove',function(e){

    if(ISGAMING === 1){
      var x = e.clientX;
      var y = e.clientY;
      hero.move(x,y)
    }

  },false)


  function palyEffect(){
    console.log(bomb.currentTime)
      if(bomb.currentTime > 0){
        bomb.currentTime = 0;
      }
      bomb.play()
  }


  function gameOver(){
    
  }

}
